<template>
  <div id="replace">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 上 -->
      <div slot="header" class="clearfix">
        <!-- 添加按钮 -->
        <el-button type="primary" @click="dialogFormVisible = true"
          >添加用户</el-button
        >
      </div>
      <!-- 角色列表区域 -->
      <el-table
        :data="roleList"
        highlight-current-row
        style="width: 100%"
        border
      >
        <!-- 添加展开列 -->
        <el-table-column type="expand"></el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              @click="handleEdit(scope.$index, scope.row)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              @click="handleDelete(scope.row)"
            ></el-button>
            <!-- 分配权限 -->
            <el-button
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
              >分配角色</el-button
            >
          </template>
        </el-table-column>
        <!-- 添加展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二，三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环嵌套渲染二级权限  -->
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      @close="removeRightById(scope.row, item2.id)"
                      closable
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      @close="setRightDialogClosed"
      width="50%"
    >
      <el-tree
        :data="rightslist"
        :default-checked-keys="defKeys"
        node-key="id"
        ref="treeRef"
        default-expand-all
        show-checkbox
        :props="treeProps"
      >
      </el-tree>
      <div slot="footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 添加用户模态框 -->
    <el-dialog title="添加角色" :visible.sync="dialogFormVisible">
      <el-form :model="form1">
        <el-form-item
          label="角色名称"
          prop="roleName"
          :rules="[
            { required: true, message: '请输入角色名称', trigger: 'blur' },
          ]"
        >
          <el-input v-model="form1.roleName"></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述"
          prop="roleDesc"
          :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]"
        >
          <el-input v-model="form1.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="add()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改用户模态框 -->
    <el-dialog title="添加角色" :visible.sync="editdialogFormVisible">
      <el-form :model="form">
        <el-form-item
          label="角色名称"
          prop="roleName"
          :rules="[
            { required: true, message: '请输入角色名称', trigger: 'blur' },
          ]"
        >
          <el-input v-model="form.roleName"></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述"
          prop="roleDesc"
          :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]"
        >
          <el-input v-model="form.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editdialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editadd()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
export default {
  props: [],
  data() {
    return {
      roleList: [],
      setRightDialogVisible: false,
      dialogFormVisible: false,
      editdialogFormVisible: false,
      rightslist: [],
      treeProps: {
        children: "children",
        label: "authName",
      },
      defKeys: [],
      roleId: "",
      form1: {
        roleName: "",
        roleDesc: "",
      },
      form: {
        roleName: "",
        roleDesc: "",
      },
    };
  },
  methods: {
    // 获取数据
    getRoleList() {
      this.$http.get("/roles").then((res) => {
        console.log(res);
        this.roleList = res.data.data;
      });
    },
    // X号删除
    removeRightById(role, rightId) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http
            .delete(`roles/${role.id}/rights/${rightId}`)
            .then((res) => {
              if (res.data.meta.status !== 200) {
                return this.$message.error(res.data.meta.msg);
              }
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              role.children = res.data.data;
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 分配角色
    showSetRightDialog(role) {
      this.roleId = role.id;
      this.$http.get("rights/tree").then((res) => {
        if (res.data.meta.status !== 200) {
          return this.$message.error(res.data.meta.msg);
        } else {
          this.rightslist = res.data.data;
          this.getLeafKeys(role, this.defKeys);
          this.setRightDialogVisible = true;
        }
      });
    },
    // 展开的节点的 key 的数组
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => this.getLeafKeys(item, arr));
    },
    setRightDialogClosed() {
      this.defKeys = [];
    },
    // 点击分配权限对话框内确认
    allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idStr = keys.join(",");
      this.$http
        .post(`roles/${this.roleId}/rights`, { rids: idStr })
        .then((res) => {
          if (res.data.meta.status !== 200) {
            return this.$message.error(res.data.meta.msg);
          }
          this.$message.success("分配权限成功！");
          this.setRightDialogVisible = false;
          this.getRoleList();
        });
    },
    // 点击添加按钮事件
    add() {
      // 拿取在线文档的添加用户  请求的参数是输入的参数时
      this.$http
        .post("/roles", {
          roleName: this.form1.roleName,
          roleDesc: this.form1.roleDesc,
        })
        .then((res) => {
          console.log(res);
          // 返回状态为201时添加成功从新喧染页面
          if (res.data.meta.status == 201) {
            this.getRoleList();
            this.form1.roleName = "";
            this.form1.roleDesc = "";
          }
        });
      // 点击修改中的确定 模态框为false关闭页面
      this.dialogFormVisible = false;
    },
    // 点击修改按钮事件
    handleEdit(index, row) {
      console.log(index, row);
      // 点击修改是 模态框为true显示页面
      this.editdialogFormVisible = true;
      // 把当前这行的id存到本地
      localStorage.setItem("id", row.id);
      // 拿取线在文档的修改用户状态的数据
      this.$http.get("roles/" + row.id).then((res) => {
        console.log(res);
        //把响应数据放在    自己定义的from对象里面对应的内容
        this.form.id = res.data.data.roleId;
        this.form.roleName = res.data.data.roleName;
        this.form.roleDesc = res.data.data.roleDesc;
      });
    },
    // 点击修改中确认按钮事件
    editadd() {
      // 定义一个值 来接收本地存储的id
      let id = localStorage.getItem("id");
      // 拿取在线文档的编辑用户提交   请求的参数是修改时输入的参数
      this.$http
        .put("/roles/" + id, {
          id: id,
          roleName: this.form.roleName,
          roleDesc: this.form.roleDesc,
        })
        .then((res) => {
          let xg = confirm("您确定要修改吗？");
          // 判断确认或取消
          if (xg) {
            // 判断状态为200是修改成功
            if (res.data.meta.status == 200) {
              // 关闭模态框
              this.editdialogFormVisible = false;
              // 显示页面
              this.getRoleList();
            }
          } else {
            //关闭模态框
            this.editdialogFormVisible = false;
          }
        });
    },
     // 点击删除按钮事件
      handleDelete(row) {
         console.log(row);
      this.$confirm("此操作将永久删除该商品, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
           this.$http.delete("roles/" + row.id).then(res=>{
             if (res.data.meta.status !== 200) {
            return this.$message.error(res.data.meta.msg);
          }
          this.getRoleList();;
          this.$message({
            type: "success",
            message: "删除成功!"
          });
           });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
  },
  created() {
    this.getRoleList();
  },
};
</script>


<style scoped>
.el-card {
  margin-top: 15px;
}
.el-table {
  margin-top: 15px;
}
</style>